package com.mrjy.maintain.bo;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.mrjy.common.entity.OperationCenterInfo;
import com.mrjy.common.entity.PromotorLink;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserScancodeInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserScancodeInfoDao;
import com.mrjy.maintain.dto.UserScancodeInfoDto;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.share.dao.IOperationCenterInfoDao;
import com.mrjy.share.dao.IPromotorLinkDao;

@Service("userScanCodeInfoBo")
public class UserScanCodeInfoBo implements IUserScanCodeInfoBo{
	
	@Resource
	private IUserScancodeInfoDao userScanCodeInfoDao;
	
	@Resource
	private IUserInfoDao userInfoDao;
	
	@Resource
	private IPromotorLinkDao promotorLinkDao;
	
	@Resource
	private IOperationCenterInfoDao operationCenterInfoDao ;

	@Override
	public Object txInsertUserScanInfo(UserScancodeInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == info || null == info.getUserId() || null == info.getUserId()){
			map.put("err_code", -1);
			map.put("err_msg", "传入参数有误");
			return map;
		}
		info.setCreateTime(new Date());
		
		//1.根据userId查询promotorLink中有没有值，有则不插入，没有，则插入。比如扫码者为A， A->B->C->D 表示A扫了B，B扫了C，C扫了D
		PromotorLink link = promotorLinkDao.selectByUserId(info.getUserId());
		if(link == null){//没有推广关系，则插入
			OperationCenterInfo oci = operationCenterInfoDao.selectByShareCode(info.getShareCode()) ;
			if(oci != null && info.getUserId().intValue() != oci.getUserId().intValue()){
				link = new PromotorLink() ;
				link.setUserId(info.getUserId());
				link.setFirstUserId(oci.getUserId());
				link.setCreateTime(new Timestamp(System.currentTimeMillis()));
				link.setLevel("0"); //默认不是运营的下级
				link.setIsOperation("0"); //默认不是运营的下级
				if(oci.getId() !=null){//则为运营中心推广的一级
					link.setLevel("1");//一级推广
					link.setIsOperation("1");//是运营中心的下级
					link.setOperationCenterId(oci.getId());
				}else{//普通的推广关系 或者为运营中心推广的二级或者三级
					//通过扫码者A的上级B的id查询扫码者的C是否为运营中心的下级
					PromotorLink firstLink = promotorLinkDao.selectByUserId(oci.getUserId());
					if(null != firstLink){
						if("1".equals(firstLink.getIsOperation())){//运营中心的下级
							if("1".endsWith(firstLink.getLevel())){
								link.setLevel("2");
								link.setIsOperation("1");
								link.setOperationCenterId(firstLink.getOperationCenterId());
							}
//							else if("2".equals(firstLink.getLevel())){
//								link.setLevel("3");
//								link.setIsOperation("1");
//								link.setOperationCenterId(firstLink.getOperationCenterId());
//							}
						}
					}
//					else{ //扫码者A的上级B没有扫C，此时直接插入A->B的关系到promotorLink表
//						
//					}
				}
				promotorLinkDao.insert(link);
			}
		}
		
		int result = userScanCodeInfoDao.insert(info);
		if(result == 1){
			map.put("err_code", 0);
			map.put("err_msg", "插入日志成功");
		}else{
			map.put("err_code", -2);
			map.put("err_msg", "失败");
		}
		return map;
	}

	@Override
	public Object queryPageByShareCode(UserScancodeInfoDto dto,UserInfo userInfo,Map<String, Object> map) {
		
		if(userInfo.getRoleId().intValue() == RoleInfoEnum.PARTNER_ADMIN.getRoleId() 
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId() 
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.SCHOOL_ADMIN.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.TEACHER.getRoleId()
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.DISTRIBUTOR_ADMIN.getRoleId()
				){//合作方管理员或者服务站管理员或者学校或者学校&服务站管理员 ,添加讲师，分销商
			dto.setShareCode(userInfo.getRecommendCode());
		}
		
		long scanUserCountTotal = userScanCodeInfoDao.scanUserCountTotal(dto);
		if(scanUserCountTotal >0){
			Long scanCountTotal = userScanCodeInfoDao.scanCountTotal(dto); //扫码日志记录数, 用于封装"total", 会随着条件变化
			Long scanCountTotal2 = userScanCodeInfoDao.scanCountTotal2(dto); //全站扫码次数,不会随着条件变化
			Long promoterCountTotal = userScanCodeInfoDao.promoterCountTotal(dto); //全站推广者人数
			List<UserScancodeInfoDto> list = userScanCodeInfoDao.queryPageByShareCode(dto);
			if(list != null && list.size() >0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("scanUserCountTotal", scanUserCountTotal);
				map.put("scanCountTotal", scanCountTotal2);
				map.put("promoterCountTotal", promoterCountTotal);
				map.put("rows", list);
				map.put("total", scanCountTotal);
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "查询成功,无数据");
				map.put("scanUserCountTotal", scanUserCountTotal);
                map.put("scanCountTotal", scanCountTotal);
                map.put("promoterCountTotal", promoterCountTotal);
				map.put("rows", list);
				map.put("total", scanCountTotal);
			}
		}else{
			map.put("err_code", 2);
			map.put("err_msg", "查询成功,无数据");
			map.put("scanUserCountTotal", scanUserCountTotal);
			map.put("scanCountTotal", 0);
			map.put("promoterCountTotal", 0);
			map.put("rows", null);
			map.put("total", 0);
		}
			
		return map;
	}

	@Override
	public Object queryTotalScanNum(UserScancodeInfoDto dto,UserInfo userInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(null == userInfo ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		
		if(userInfo.getRoleId().intValue() == RoleInfoEnum.PARTNER_ADMIN.getRoleId() 
				|| userInfo.getRoleId().intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId() ){//合作方管理员或者服务站管理员
			dto.setShareCode(userInfo.getRecommendCode());
		}
		
		Long scanUserCountTotal = userScanCodeInfoDao.scanUserCountTotal(dto);
		Long scanCountTotal = 0L;
		if(scanUserCountTotal > 0){
			scanCountTotal = userScanCodeInfoDao.scanCountTotal(dto);
		}
		map.put("err_code", 0);
		map.put("err_msg", "查询成功");
		map.put("scanUserCountTotal", scanUserCountTotal);
		map.put("scanCountTotal", scanCountTotal);
		return map;
	}
/*
	@Override
	public Object queryPage(UserScancodeInfoDto dto, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == userInfo ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if(userInfo.getRoleId() == 9 || userInfo.getRoleId() == 8 ){//合作方管理员或者服务站管理员
			dto.setShareCode(userInfo.getRecommendCode());
		}
		
		Long scanUserCountTotal = userScanCodeInfoDao.scanUserCountTotal(dto);
		Long scanCountTotal = userScanCodeInfoDao.scanCountTotal(dto);
		List<UserScancodeInfoDto> list = userScanCodeInfoDao.queryPageByShareCode(dto);
		if(list != null && list.size() > 0){
			
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("scanUserCountTotal", scanUserCountTotal);
			map.put("scanCountTotal", scanCountTotal);
			map.put("rows", newList);
			map.put("total", scanCountTotal);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "查询成功,无数据");
			map.put("scanUserCountTotal", scanUserCountTotal);
			map.put("scanCountTotal", scanCountTotal);
			map.put("rows", newList);
			map.put("total", scanCountTotal);
		}	
		
		return map;
	}
*/
	@Override
	public Object export(UserScancodeInfoDto info, HttpServletResponse response,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if(loginUser.getRoleId().intValue() == RoleInfoEnum.PARTNER_ADMIN.getRoleId() 
				|| loginUser.getRoleId().intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId() 
				|| loginUser.getRoleId().intValue() == RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId() ){//合作方管理员或者服务站管理员或者学校&服务站管理员
			info.setShareCode(loginUser.getRecommendCode());
		}
		List<UserScancodeInfoDto> dataset = userScanCodeInfoDao.queryPageByShareCode(info);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		try {
			ExcelUtil.writeExcel(response, "扫码日志"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, UserScancodeInfoDto.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}
	
}
